package com.erp.module.crm.xXCrm

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.provider.MediaStore
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.PopupWindow
import android.widget.RelativeLayout
import androidx.appcompat.app.AlertDialog
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.activity.ChaKanTuZhiAvtivity
import com.erp.activityKView.CrmFKView
import com.erp.bean.ClientGaugeBean
import com.erp.myAdapter.FileAdapter
import com.erp.myAdapter.PhotoAdapter
import com.erp.myFragment.BaseKFragment
import com.erp.permission.PermissionListener
import com.erp.popupwin.PopShejiXiaoshouDuoxuan
import com.erp.util.*
import kotlinx.android.synthetic.main.fragment_clienttwo.*
import kotlinx.android.synthetic.main.pop_address_picker.view.*
import org.json.JSONArray
import org.json.JSONObject


/**
 * Created by Administrator on 2016/11/2 0002.
 * 量尺信息
 */
@SuppressLint("ValidFragment")
class FragmentClienttwo : BaseKFragment, View.OnClickListener {
    lateinit var clientGaugeBean: ClientGaugeBean ;
    lateinit var FKP : CrmFKView;
    constructor(){
    }
    constructor( FKP: CrmFKView, clientGaugeBean: ClientGaugeBean){
        this.clientGaugeBean=clientGaugeBean
        this.FKP = FKP
    }

    private val f = "FragmentClienttwo"
    lateinit var gvaapter: PhotoAdapter
    lateinit var gvfileaapter: FileAdapter
    private var name: String = ""
    var province =""
    var city =""
    var country = ""
    var street = ""
    var detailed_address = ""
    var mxuanzhongid : MutableList<String> = ArrayList()
    override fun getLayoutId(): Int {
        fragmentname = f
        return R.layout.fragment_clienttwo
    }

    fun initView() {
        gvfileaapter= FileAdapter(activity!!,clientGaugeBean.listfile,false)
//        gvfileaapter = GvfileAdapter(clientGaugeBean.filelist, activity)
        GvGaugeFile.adapter = gvfileaapter
        gvaapter= PhotoAdapter(activity!!,clientGaugeBean.listphoto,true)
//        gvaapter = GaugeivGvAdapter1(clientGaugeBean.listimgbean, activity!!)
        GvGaugeImg.adapter = gvaapter
    }

    override fun initData() {
        initView()
        initClick()
        initsData()
    }

    private fun initClick() {
        BtBaocun.setOnClickListener(this)
        LlGaugeYuyue.setOnClickListener(this)
        LlAddr.setOnClickListener(this)
        LlGaugeLiangchi.setOnClickListener(this)
        LlGaugeFuchi.setOnClickListener(this)
        LlGaugeShejishi.setOnClickListener(this)
        /**
         * 删除图片
         */
        GvGaugeImg.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
//            if(position<clientGaugeBean.listphoto.size) {
//                val listid = ArrayList<String>()
//                for (i in 0 until clientGaugeBean.listfid.size) {
//                    if (clientGaugeBean.listfid[i] != clientGaugeBean.listphoto[position].fid) {
//                        listid.add(clientGaugeBean.listfid[i])
//                    }
//                }
//                Dialogutil.longitem(activity, listid, "measuring_scale",FKP)
//                true
//            }else{
                true
//            }
        }
        /**
         * 查看图片
         */
        GvGaugeImg.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            if(position<clientGaugeBean.listphoto.size) {
                val intent = Intent(activity, ChaKanTuZhiAvtivity::class.java)
                val urls : ArrayList<String> = ArrayList()
                urls.add(clientGaugeBean.listphoto[position].uri)
                intent.putStringArrayListExtra("url", urls)
                startActivity(intent)
            }else if(clientGaugeBean.listphoto.size==position){

                Dialogutil.zhiphoto(activity, this@FragmentClienttwo)
//                Dialogutil.photodialog(activity, this@FragmentClienttwo)
            }
        }
        /**
         * 下载附件
         */
        GvGaugeFile.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            PermissionUtils.isupdate(activity!!, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
//                    Dialogutil.downloaddialog(clientGaugeBean.filelist[position], activity)
                    Dialogutil.downloaddialog1(clientGaugeBean.listfile[position], activity)
                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法下载")
                }
            })
        }
    }

    lateinit var updatedialog : AlertDialog
    override fun onClick(v: View?) {
        when(v){
            BtBaocun -> {
                val jo=xiugai()
                updatedialog= Myutil.showupdatedialog(context, "正在保存", false)
                Httputil.cleanclient(activity, ClientKActivity.getid(),jo,object : OnUserDataInterface{
                    override fun onUserData(data: String?) {
                        updatedialog.dismiss()
                        if(data==null){
                            Myutil.MyTost("保存失败")
                            return
                        }
                        Myutil.MyTost("保存成功")
                        FKP.updata(data)
                    }

                    override fun onNot(throwable: String?) {
                        updatedialog.dismiss()
                        Log.d("TAAAG","throwable="+throwable)
                    }

                })
            }
            LlGaugeYuyue -> {
                Dialogutil.showBottoPopupWindow(TvGaugeYuyue, "选择预约量尺时间", TvGaugeYuyue.text.toString(), activity)
            }
            LlAddr -> {
                val popupWindow = PopupWindow(context)
                val rootView = LayoutInflater.from(activity).inflate(R.layout.pop_address_picker, null, false)
                rootView.apvAddress.setOnAddressPickerSure { address, provinceCode, cityCode, districtCode ->
                    TvAddr.text = address
                    province=provinceCode
                    city=cityCode
                    country=districtCode
                    street=""
                    popupWindow.dismiss()
                }
                rootView.apvAddress.dizhiData();
                popupWindow.contentView = rootView
                popupWindow.isFocusable = true
                popupWindow.isOutsideTouchable = true
                val params = rootView.apvAddress.layoutParams as RelativeLayout.LayoutParams
                params.height = sp.getInt("height",0)/2//设置当前控件布局的高度
                rootView.apvAddress.layoutParams = params//将设置好的布局参数应用到控件中
                popupWindow.animationStyle = R.style.showPopupAnimation
                popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
                popupWindow.height = sp.getInt("height",0)*5/10
                popupWindow.showAtLocation(TvAddr, Gravity.BOTTOM, 0, 0)
            }
//            LlXiangXiAddr -> {
//                val i =Intent(activity, SeekActivity:: class.java)
//                i.putExtra("select",0)
//                i.putExtra("title","详细地址")
//                i.putExtra("data",TvXiangXiAddr.text)
//                this@FragmentClienttwo.startActivityForResult(i,50)
//            }
            LlGaugeLiangchi -> {
                Dialogutil.showBottoPopupWindow(TvGaugeLiangchi, "选择量尺时间", TvGaugeLiangchi.text.toString(), activity)
            }
            LlGaugeFuchi -> {
                Dialogutil.showBottoPopupWindow(TvGaugeFuchi, "选择复尺时间", TvGaugeFuchi.text.toString(), activity)
            }
            LlGaugeShejishi -> {
                val  pop = PopShejiXiaoshouDuoxuan(context!!,PopShejiXiaoshouDuoxuan.XSY,clientGaugeBean.shejishi,object : PopShejiXiaoshouDuoxuan.duoxuan{
                    override fun xuanze(list: MutableList<String>, listid: MutableList<String>) {
                        val shejishi = StringBuffer("")
                        for (j in 0 until list.size) {
                            if (j == list.size - 1) {
                                shejishi.append(list[j])
                            } else {
                                shejishi.append(list[j])
                                shejishi.append("\n")
                            }
                        }
                        Myutil.settv(shejishi.toString(), TvGaugeShejishi)
                        mxuanzhongid=listid
                    }

                },"请选择设计师")
                pop.show(sp,TvGaugeShejishi)
            }
        }
    }

    private fun xiugai(): JSONObject {
        var jo = JSONObject()
        try {
            val measuring_scale = JSONObject()
            measuring_scale.put("appointment_measuring_time", TvGaugeYuyue.text.toString())
            measuring_scale.put("measuring_time", TvGaugeLiangchi.text.toString())
            measuring_scale.put("remeasuring_time", TvGaugeFuchi.text.toString())
            val joaddr = JSONObject()
            joaddr.put("province",province)
            joaddr.put("city",city)
            joaddr.put("country",country)
            joaddr.put("street",street)
            joaddr.put("detailed_address",EtXiangXiAddr.text.toString())
            measuring_scale.put("addr",joaddr)
            if(TvGaugeShejishi.text.toString()!="") {
                val js = JSONArray()
                for (s in mxuanzhongid) {
                    js.put(s)
                }
                measuring_scale.put("designer", js)
            }
            jo.put("measuring_scale", measuring_scale)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.d("TAAAG","--------------"+e.toString())
        }

        return jo
    }

    private fun initsData() {
        Myutil.settv(Myutil.getdata(clientGaugeBean.appointment_measuring_time), TvGaugeYuyue)
        Myutil.settv(Myutil.getdata(clientGaugeBean.measuring_time), TvGaugeLiangchi)
        Myutil.settv(Myutil.getdata(clientGaugeBean.remeasuring_time), TvGaugeFuchi)
        Log.d("ADDR","addr="+clientGaugeBean.addr)
        try {
            val jo = JSONObject(clientGaugeBean.addr)
            province=JsonUtil.getvolue(jo,"province")
            city=JsonUtil.getvolue(jo,"city")
            country=JsonUtil.getvolue(jo,"country")
            street=JsonUtil.getvolue(jo,"street")
            detailed_address=JsonUtil.getvolue(jo,"detailed_address")
        } catch (e: Exception) {
            e.printStackTrace()
        }
        TvAddr.text= "$province  $city  $country  $street"
        Myutil.setet(detailed_address,EtXiangXiAddr)
        if (clientGaugeBean.shejishi.size != 0) {
                val shejishi = StringBuffer("")
                for (j in 0 until clientGaugeBean.shejishi.size) {
                    if (j == clientGaugeBean.shejishi.size - 1) {
                        shejishi.append(clientGaugeBean.shejishi[j])
                    } else {
                        shejishi.append(clientGaugeBean.shejishi[j])
                        shejishi.append("\n")
                    }
                }
                Myutil.settv(shejishi.toString(), TvGaugeShejishi)
            }
        Log.d("clientGaugeBean","clientGaugeBean.listphoto="+clientGaugeBean.listphoto.toString())
        if(!isFirstLoad){
            gvfileaapter.Allnotify(clientGaugeBean.listfile)
            gvaapter.Allnotify(clientGaugeBean.listphoto)
//            gvfileaapter.Allnotify(clientGaugeBean.filelist)
//            gvaapter.Allnotify(clientGaugeBean.listimgbean)
        }
    }

    fun notifydata() {
        initsData()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(data==null){
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                100 -> {
                    name = data.getStringExtra("dir")
                    val listid = ArrayList<String>()
                    for (i in 0 until clientGaugeBean.listimgbean.size) {
                        listid.add(clientGaugeBean.listimgbean[i].imgid)
                    }
                    val jo=xiugai()
                    Dialogutil.previewdialog(activity, clientGaugeBean.listfid, name, "measuring_scale",jo, FKP)
                }
                99 -> {
                    val selectedImage = data.data
                    val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                    if(selectedImage != null){
                        val c = context!!.contentResolver.query(selectedImage, filePathColumns, null, null, null)
                        c!!.moveToFirst()
                        val columnIndex = c.getColumnIndex(filePathColumns[0])
                        val imagePath = c.getString(columnIndex)
                        val listid = ArrayList<String>()
                        for (i in 0 until clientGaugeBean.listimgbean.size) {
                            listid.add(clientGaugeBean.listimgbean[i].imgid)
                        }
                        val jo=xiugai()
                        Dialogutil.previewdialog(activity, clientGaugeBean.listfid, imagePath, "measuring_scale",jo, FKP)
                    }

                }
//                50 -> {
//                    TvXiangXiAddr.text=data.getStringExtra("name")
//                }
            }
        }
    }




}
